import React, { useEffect, useRef, useState } from 'react';
import TRNotification from '@/utils/notification';
import { Button, Form, Input, InputNumber, Modal, Select, Space } from 'antd';
import { useSetState } from 'ahooks';
import styles from './index.less';
import moment from 'moment';
import { editSaveContract, saveAddContract, templateSearch } from '../../services';
import { AddTable } from './components/addTable';
import {
  buildAddResult,
  countTotal,
  getAccessId,
  judgeIsTime,
  objToArr,
  POWER_ENUM,
} from './helper';
import { HttpCode } from '@/utils/contacts';
import { Template } from './components/template';
import { TRAlert, TRMessage } from '@/components';
import CiteTemplateModal from './components/citeTemplate';
import { createFromIconfontCN } from '@/utils/antdIcons';

const MyIcon = createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1635810_54zp3na6k9q.js',
});

const AddModalComponent = ({
  onClose,
  pageQuery = {},
  counterPartyList = [],
  menuCode,
  type = 'add',
  contractData = {},
}) => {
  // 调整为
  const adjustValue = useRef(0);
  // 调整比例为
  const adjustScaleValue = useRef(0);

  const [titleData, setTitleData] = useSetState({
    // 合约名称
    contractName: '新合约',
    // 对手方
    counterpartyId: null,
  });

  // 表格的所有数据
  const [tableData, setTableData] = useSetState({
    allDataIds: [],
    quantityCheckedIds: [],
    priceCheckedIds: [],
    dataSource: [],
    dataSourceObj: {},
  });

  // 当type为0时是修改模板名称，为1时是保存模板
  const [templateData, setTemplateData] = useSetState({
    type: 0,
    list: [],
    visible: false,
    editData: {},
    saveBtnDis: true,
  });

  // 关闭警告
  const [closeWarning, setCloseWarning] = useState(false);

  // 是否为新增
  const [isAdd, setIsAdd] = useState(true);

  const [saveBtnDis, setSaveBtnDis] = useState(true);

  const [loading, setLoading] = useState(false);

  const [saveLoading, setSaveLoading] = useState(false);

  const [total, setTotal] = useState({
    allTotal: {
      quantity: 0,
      price: 0,
    },
    dayTotal: {
      quantity: 0,
      price: 0,
    },
  });

  useEffect(() => {
    fetch();
  }, []);

  useEffect(() => {
    if (type === 'edit') {
      setTitleData({
        // 合约名称
        contractName: contractData.contractName,
        // 对手方
        counterpartyId: contractData.counterpartyId,
      });
      setIsAdd(false);
    }
  }, [type]);

  useEffect(() => {
    const arr = objToArr(tableData.dataSourceObj);
    // 拿到dataSource所有id
    const ids = getDataSourceIds(arr);
    // 统计日总计和总计
    const { sum, priceSum } = countTotal(arr);
    setTotal({
      ...total,
      allTotal: { quantity: sum, price: priceSum },
      dayTotal: { quantity: sum, price: priceSum },
    });
    setTableData({ dataSource: arr, allDataIds: ids });
    if (arr.length !== 0) {
      setCloseWarning(true);
    }
  }, [JSON.stringify(tableData.dataSourceObj)]);

  useEffect(() => {
    // 根据表格的数据放开保存按钮的限制
    if (tableData?.dataSource) {
      setSaveBtnDis(!judgeIsTime(tableData.dataSource || [], false));
    }
  }, [tableData.dataSource]);

  const getDataSourceIds = (arr) => {
    return arr.map((i) => i.id);
  };

  const fetch = async () => {
    setLoading(true);
    // templateSearch获取套用模板列表
    const res = await templateSearch();
    if (res.statusCode === HttpCode.SUCCESS) {
      setTemplateData({
        list: res?.results || [],
      });
    } else {
      TRMessage.error(res?.message || '系统异常');
    }
    setLoading(false);
  };

  const handleCancel = (checked = false) => {
    if (closeWarning && checked) {
      Modal.confirm({
        style: { top: '30%' },
        title: '当前工作将不被保存，继续执行此操作?',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          onClose();
        },
      });
    } else {
      onClose();
    }
  };

  const closeTooltip = (e) => {
    e && e.stopPropagation();
    const obj = tableData.dataSourceObj;
    for (let k in obj) {
      obj[k] = { ...obj[k], showTimePicker: false };
    }
    setTableData({ dataSourceObj: obj });
  };

  const addDataSource = () => {
    let { dataSourceObj } = tableData;
    const id = getAccessId(dataSourceObj);
    dataSourceObj[id] = {
      id,
      [POWER_ENUM.POWER_COUNT]: '0.000',
      [POWER_ENUM.POWER_PRICE]: '0.0',
      startTime: '',
      endTime: '',
      key: '',
    };
    setTableData({ dataSourceObj });
  };

  const changeValue = (v, type) => {
    // type为0的时候是直接复制为1的时候为比例调整
    if (type) {
      adjustScaleValue.current = v;
    } else {
      adjustValue.current = v;
    }
  };

  // 根据input框的值修改选中的单元格的值
  const changeAllSelectValue = (type) => {
    // type为0的时候是直接复制为1的时候为比例调整
    let value = type ? adjustScaleValue.current : adjustValue.current;
    value = isNaN(Number(value)) ? 0 : Number(value);
    const obj = tableData.dataSourceObj;
    const { quantityCheckedIds, priceCheckedIds } = tableData;
    if (type) {
      quantityCheckedIds.forEach((i) => {
        let quantity = Number(obj?.[i]?.[POWER_ENUM.POWER_COUNT]);
        quantity = isNaN(quantity) ? 0 : quantity;
        obj[i][POWER_ENUM.POWER_COUNT] = ((quantity * value) / 100).toFixed(3);
      });
      priceCheckedIds.forEach((i) => {
        let price = Number(obj?.[i]?.[POWER_ENUM.POWER_PRICE]);
        price = isNaN(price) ? 0 : price;
        obj[i][POWER_ENUM.POWER_PRICE] = ((price * value) / 100).toFixed(1);
      });
    } else {
      quantityCheckedIds.forEach((i) => {
        obj[i][POWER_ENUM.POWER_COUNT] = value.toFixed(3);
      });
      priceCheckedIds.forEach((i) => {
        obj[i][POWER_ENUM.POWER_PRICE] = value.toFixed(1);
      });
    }
    setTableData({ dataSourceObj: obj });
  };

  // 保存模板
  const handleSaveTemplate = () => {
    // 校验是否所有行都选择了时间段
    if (judgeIsTime(tableData.dataSource)) {
      setTemplateData({
        type: 1,
        visible: true,
        editData: {},
      });
    }
  };

  const handleCiteTemplate = () => {
    CiteTemplateModal.show({ pageQuery, menuCode, setTableData });
  };

  const handleSave = async () => {
    if (!titleData.contractName || !titleData.counterpartyId) {
      TRMessage.error('合约名和对手方不能为空!');
      return;
    }
    setSaveLoading(true);
    const results = buildAddResult(tableData.dataSource);
    const params = {
      contractName: titleData.contractName,
      counterpartyId: titleData.counterpartyId,
      endDate: pageQuery.en,
      startDate: pageQuery.st,
      stationId: pageQuery.s,
      results,
    };
    if (isAdd) {
      const res = await saveAddContract(params);
      if (res.statusCode === HttpCode.SUCCESS) {
        TRMessage.success('保存成功!');
        handleCancel();
      } else {
        await TRAlert.warning(res?.message || '');
      }
    } else {
      params.contractId = contractData.contractId;
      const res = await editSaveContract(params);
      if (res.statusCode === HttpCode.SUCCESS) {
        TRMessage.success('保存成功!');
        handleCancel();
      } else {
        await TRAlert.warning(res?.message || '');
      }
    }
    setSaveLoading(false);
  };

  const contractNameChange = (e) => {
    setTitleData({
      contractName: e.target.value,
    });
  };

  const changeCounterpartyId = (v) => {
    setTitleData({
      counterpartyId: v,
    });
  };

  const _getTitle = () => {
    const width = 200;
    return (
      <div>
        <Space size={16}>
          <span>
            日期: {moment(pageQuery?.st).format('YYYYMMDD')}-
            {moment(pageQuery?.en).format('YYYYMMDD')}
          </span>
          <Input
            style={{ width }}
            value={titleData.contractName}
            onChange={contractNameChange}
            disabled={!isAdd}
          />
          <Select
            style={{ width }}
            placeholder={'请选择对手方'}
            value={titleData.counterpartyId}
            onChange={changeCounterpartyId}
            disabled={!isAdd}
            showSearch
            filterOption={(input, option) =>
              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
          >
            {counterPartyList.map((i) => (
              <Select.Option key={i.id} value={i.id}>
                {i.counterpartyName}
              </Select.Option>
            ))}
          </Select>
        </Space>
        <div className={styles.warningIcon}>
          {!isAdd && (
            <>
              <MyIcon type={'iconjinggao'} className={styles.icon} />
              注意：若时间段、电量、电价不一致时,页面将显示日期范围第一天合约数据！
            </>
          )}
        </div>
      </div>
    );
  };

  const _leftHead = () => {
    const width = 90;
    return (
      <div className={styles.rightHead}>
        <Space size={16}>
          <Form.Item label={'调节为'}>
            <Input
              style={{ width }}
              onChange={(e) => changeValue(e.target.value, 0)}
              onBlur={() => changeAllSelectValue(0)}
            />
          </Form.Item>
          <Form.Item label={'调节比例'}>
            <InputNumber
              onChange={(v) => changeValue(v, 1)}
              style={{ width }}
              min={0}
              max={100}
              formatter={(v) => `${v}%`}
              parser={(v) => v?.replace('%', '')}
              onBlur={() => changeAllSelectValue(1)}
            />
          </Form.Item>
        </Space>
        <Button type="primary" ghost onClick={addDataSource}>
          添加
        </Button>
      </div>
    );
  };

  const _totalEl = () => {
    const dayQuantity = total.dayTotal.quantity.toFixed(3);
    const dayPrice = total.dayTotal.price.toFixed(1);
    const totalQuantity = total.allTotal.quantity.toFixed(3);
    const totalPrice = total.allTotal.price.toFixed(1);
    return (
      <div className={styles.addTotal}>
        <div className={styles.totalLine}>
          <span>日总计</span>
          <span>{dayQuantity}</span>
          <span>{dayPrice}</span>
        </div>
        <div className={styles.totalLine}>
          <span>总计</span>
          <span>{totalQuantity}</span>
          <span>{totalPrice}</span>
        </div>
      </div>
    );
  };

  return (
    <Modal
      wrapClassName={styles.addModal}
      visible={true}
      onCancel={() => handleCancel(true)}
      width={'850px'}
      maskClosable={false}
      title={_getTitle()}
      centered
      footer={null}
    >
      <div className={styles.addContent} onClick={closeTooltip}>
        <div className={styles.addLeft}>
          {_leftHead()}
          <div>
            <AddTable loading={loading} setTableData={setTableData} tableData={tableData} />
          </div>
          {_totalEl()}
          <div className={styles.addFoot}>
            <Space size={16}>
              <a onClick={handleSaveTemplate}>存为模版</a>
              <a onClick={handleCiteTemplate}>引用合约</a>
            </Space>
            <Space size={16}>
              <Button onClick={() => handleCancel(true)}>取消</Button>
              <Button
                type="primary"
                onClick={handleSave}
                loading={saveLoading}
                disabled={saveBtnDis}
              >
                保存
              </Button>
            </Space>
          </div>
        </div>
        <div className={styles.addRight}>
          <Template
            dataSource={tableData.dataSource}
            loading={loading}
            getTemplate={fetch}
            setTemplateData={setTemplateData}
            templateData={templateData}
            setTableData={setTableData}
          />
        </div>
      </div>
    </Modal>
  );
};

class AddModal {
  __key__ = '';
  show = (props) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <AddModalComponent
            {...props}
            onClose={() => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve();
            }}
          />
        ),
        duration: null,
      });
    });
  };
  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new AddModal();
